package com.wd.tw.utils;

import com.digitalpetri.modbus.codec.Modbus;
import com.digitalpetri.modbus.master.ModbusTcpMaster;
import com.digitalpetri.modbus.master.ModbusTcpMasterConfig;
import com.digitalpetri.modbus.requests.ReadHoldingRegistersRequest;
import com.digitalpetri.modbus.responses.ReadHoldingRegistersResponse;
import io.netty.buffer.ByteBuf;
import io.netty.util.ReferenceCountUtil;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class ModbusMasterTcpReader {

    static ModbusTcpMaster tcpMaster;

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        initModbusMasterTcp();
        Number number = readHoldingRegisters(0, 10, 1);
        System.out.println(number.toString());
        release();
    }
    // 初始化
    public static void initModbusMasterTcp(){
        // 创建匹配，添加信息
        ModbusTcpMasterConfig tcpMasterConfig = new ModbusTcpMasterConfig
                .Builder("192.168.100.204")
                .setPort(503)
                .build();
        tcpMaster = new ModbusTcpMaster(tcpMasterConfig);
        tcpMaster.connect();
    }

    public static Number readHoldingRegisters(int serverAddress, int quantity, int unitId) throws ExecutionException, InterruptedException {
        Number result = null;
        CompletableFuture<ReadHoldingRegistersResponse> future = tcpMaster
                .sendRequest(new ReadHoldingRegistersRequest(serverAddress, quantity), unitId);

        // 同步执行
        ReadHoldingRegistersResponse response = future.get();
        if (response != null){
            ByteBuf registers = response.getRegisters();
            System.out.println(registers);
            int i = registers.readInt();
            System.out.println(i);
            result = registers.readFloat();
            ReferenceCountUtil.release(response);
        }
        return result;
    }
    // 释放资源
    public static void release(){
        if (tcpMaster != null){
            tcpMaster.disconnect();
        }
        Modbus.releaseSharedResources();
    }
}
